package com.xiaobias.dao001;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射的例子.
 *
 * @author <a href="mailto:197772517@qq.com">longw.dr</a>
 * @date 2023-11-01 10-47
 * @since 1.0
 */
public class ReflectionExample {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException,
            InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 获取 Class 对象
        Class<?> clazz = String.class;
        // 获取构造函数
        Constructor<?> constructor = clazz.getConstructor(String.class);
        // 创建对象
        String str = (String) constructor.newInstance("hello world");
        // 获取方法
        Method method = clazz.getMethod("length");
        // 调用方法
        int length = (int) method.invoke(str);
        // 获取字段
        Field field = clazz.getDeclaredField("value");
        // 设置字段的值
        field.set(field, "hello reflection");
        // 输出结果
        // 输出 hello reflection
        System.out.println(str);
        // 输出 11
        System.out.println(length);
    }
}
